package com.cordwood.starter.flyway;

import org.flywaydb.core.api.configuration.FluentConfiguration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayConfigurationCustomizer;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
public class FlywayAutoConfiguration implements FlywayConfigurationCustomizer{


    private final DataSource dataSource;

    private final boolean isDev;

    public FlywayAutoConfiguration(DataSource dataSource, Environment environment) {
        this.dataSource = dataSource;
        this.isDev = Arrays.asList(environment.getActiveProfiles()).contains("dev");
    }

    @Override
    public void customize(FluentConfiguration configuration) {
        configuration
                .outOfOrder(isDev)
                .dataSource(dataSource)
                .placeholderReplacement(false);
    }

    @Profile("dev")
    @Bean
    public FlywayMigrationStrategy repairFirstMigrateStrategy() {
        return flyway -> {
            flyway.repair();
            flyway.migrate();
        };
    }
}
